<template>
  <div>
    <el-card>
      <template #header>
        <h2>添加账号</h2>
      </template>
      <div>
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="60px"
          class="demo-ruleForm"
          size="mini"
        >
          <el-form-item label="账号" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="pass">
            <el-input
              type="password"
              v-model="ruleForm.pass"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户组">
            <el-select
              v-model="ruleForm.userGroup"
              clearable
              placeholder="请选择"
            >
              <el-option label="超级管理员" value="超级管理员"> </el-option>
              <el-option label="普通管理员" value="普通管理员"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')"
              >添加</el-button
            >
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { checkName, checkPass } from '../../utils/validate.js'
import { addUsers } from '../../api/users.js'
export default {
  data() {
    return {
      ruleForm: {
        name: '',
        pass: '',
        userGroup: ''
      },
      rules: {
        name: [{ validator: checkName, trigger: 'blur' }],
        pass: [{ validator: checkPass, trigger: 'blur' }]
      }
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          const data = await addUsers({
            account: this.ruleForm.name,
            password: this.ruleForm.pass,
            userGroup: this.ruleForm.userGroup
          })
          if (data.code === 0) {
            this.$message({
              showClose: true,
              message: data.msg,
              type: 'success'
            })
            // 清空本地数据
            this.resetForm('ruleForm')
            this.$router.push('/account/list')
          }
          // console.log(data)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.el-input {
  width: 240px;
}
</style>
